package com.weishenai.customerassistant.controller.sys;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.weishenai.customerassistant.common.Result;
import com.weishenai.customerassistant.controller.BaseController;
import com.weishenai.customerassistant.entity.sys.SysRoleEntity;
import com.weishenai.customerassistant.entity.sys.SysRoleMenuEntity;
import com.weishenai.customerassistant.entity.sys.SysUserRoleEntity;
import com.weishenai.customerassistant.service.SysRoleMenuService;
import com.weishenai.customerassistant.service.SysRoleService;
import com.weishenai.customerassistant.service.SysUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author weishenai
 * @since 2021-11-27
 */
@Api(tags = "管理系统 角色管理")
@Slf4j
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends BaseController {
    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    /**
     * @Description: 获取角色信息
     * @Param: [name, currentPage, pageSize]
     * @return: com.weishenai.blog.common.lang.Result
     * @Author: weishenai
     * @Date: 2021/12/12
     */
    @ApiOperation("获取角色信息(分页)")
    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/list")
    public Result getRoleList(@RequestParam(required = false) String name, @RequestParam Integer currentPage, @RequestParam Integer pageSize) {
        return Result.success(sysRoleService.getRoleList(name, currentPage, pageSize));
    }

    @ApiOperation("获取角色信息(无分页)")
    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/RoleList")
    public Result getRoleList() {
        return Result.success(sysRoleService.list());
    }

    /**
     * @Description: 通过id 获取菜单信息
     * @Param: [id]
     * @return: com.weishenai.blog.common.lang.Result
     * @Author: weishenai
     * @Date: 2021/12/12
     */
    @ApiOperation("通过角色id 获取菜单信息")
    @ApiImplicitParam(name = "id", value = "角色id")
    @PreAuthorize("hasAuthority('sys:role:list')")
    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long id) {
        if (id == 0) {
            return Result.success("");
        }
        SysRoleEntity sysRole = sysRoleService.getById(id);

        // 获取角色相关联的菜单id
        List<SysRoleMenuEntity> roleMenus = sysRoleMenuService.list(
                Wrappers.lambdaQuery(SysRoleMenuEntity.class)
                        .eq(SysRoleMenuEntity::getRoleId, id));
        List<Long> menuIds = roleMenus.stream().map(p -> p.getMenuId()).collect(Collectors.toList());

        sysRole.setMenuIds(menuIds);
        return Result.success(sysRole);
    }

    /***
     * @Description: 授权
     * @Param: [menuIds, roleId]
     * @return: com.weishenai.blog.common.lang.Result
     * @Author: weishenai
     * @Date: 2021/12/11
     */
    @ApiOperation("授权")
    @ApiImplicitParam(name = "roleId", value = "角色id")
    @PreAuthorize("hasAuthority('sys:role:perm')")
    @PostMapping("/permission/{roleId}")
    public Result perm(@RequestBody Long[] menuIds, @PathVariable("roleId") Long roleId) {
        List<SysRoleMenuEntity> roleMenus = new ArrayList<>();
        Arrays.stream(menuIds).forEach(menuId -> {
            SysRoleMenuEntity roleMenu = new SysRoleMenuEntity();
            roleMenu.setMenuId(menuId);
            roleMenu.setRoleId(roleId);
            roleMenus.add(roleMenu);
        });
        //先删除原来的记录，后添加新记录
        sysRoleMenuService.remove(Wrappers.lambdaQuery(SysRoleMenuEntity.class)
                .eq(SysRoleMenuEntity::getRoleId, roleId));
        sysRoleMenuService.saveBatch(roleMenus);

        // 删除缓存
        sysUserService.clearUserAuthorityInfoByRoleId(roleId);
        return Result.success(menuIds);
    }

    @ApiOperation("添加或更新角色信息")
    @PreAuthorize("hasAuthority('sys:role:save')")
    @PostMapping("/save")
    public Result save(@Validated @RequestBody SysRoleEntity sysRole) {
//        如果id为空则插入，有则更新
        if (sysRole.getId() == null) {
            sysRoleService.save(sysRole);
            return Result.success(sysRole);
        }
        sysRoleService.updateById(sysRole);
        // 更新缓存
        sysUserService.clearUserAuthorityInfoByRoleId(sysRole.getId());
        return Result.success(sysRole);
    }

    @ApiOperation("删除角色")
    @PreAuthorize("hasAuthority('sys:role:delete')")
    @PostMapping("/delete")
    public Result deleteInfo(@RequestBody Long id) {
        sysRoleService.removeById(id);
        // 删除中间表
        sysUserRoleService.remove(Wrappers.lambdaQuery(SysUserRoleEntity.class).in(SysUserRoleEntity::getRoleId, id));
        sysRoleMenuService.remove(Wrappers.lambdaQuery(SysRoleMenuEntity.class).in(SysRoleMenuEntity::getRoleId, id));

        // 缓存同步删除
        sysUserService.clearUserAuthorityInfoByRoleId(id);
        return Result.success("");
    }

}